import axios from 'axios';
import type { Message, Model, ChatSession } from '../types/chat';

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

export const chatApi = {
  // 获取可用模型列表
  getModels: async (): Promise<Model[]> => {
    try {
      const response = await apiClient.get('/api/models');
      return response.data;
    } catch (error) {
      console.error('Error fetching models:', error);
      return [];
    }
  },

  // 发送消息（流式）
  sendMessageStream: async (
    message: string,
    model: string,
    sessionId: string | undefined,
    onChunk: (chunk: string) => void,
    onSessionId: (sessionId: string) => void,
  ): Promise<string> => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/chat/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message,
          model,
          sessionId,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let fullContent = '';

      if (!reader) {
        throw new Error('No reader available');
      }

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            try {
              const parsed = JSON.parse(data);
              if (parsed.sessionId && parsed.type === 'session') {
                onSessionId(parsed.sessionId);
              } else if (parsed.content) {
                fullContent += parsed.content;
                onChunk(parsed.content);
              } else if (parsed.done) {
                return fullContent;
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      }

      return fullContent;
    } catch (error: any) {
      console.error('Error sending message stream:', error);
      throw new Error(error.message || '发送消息失败，请稍后重试');
    }
  },

  // 获取所有会话
  getSessions: async (): Promise<ChatSession[]> => {
    try {
      const response = await apiClient.get('/api/sessions');
      return response.data.map((session: any) => ({
        id: session.id,
        title: session.title,
        model: session.model,
        messages: [],
        createdAt: new Date(session.createdAt),
        updatedAt: new Date(session.updatedAt),
      }));
    } catch (error) {
      console.error('Error fetching sessions:', error);
      return [];
    }
  },

  // 获取单个会话
  getSession: async (sessionId: string): Promise<ChatSession | null> => {
    try {
      const response = await apiClient.get(`/api/sessions/${sessionId}`);
      const session = response.data;
      return {
        id: session.id,
        title: session.title,
        model: session.model,
        messages: session.messages.map((msg: any) => ({
          id: `${sessionId}-${msg.timestamp}`,
          role: msg.role,
          content: msg.content,
          timestamp: new Date(msg.timestamp),
        })),
        createdAt: new Date(session.createdAt),
        updatedAt: new Date(session.updatedAt),
      };
    } catch (error) {
      console.error('Error fetching session:', error);
      return null;
    }
  },

  // 创建新会话
  createSession: async (model: string, title?: string): Promise<ChatSession> => {
    try {
      const response = await apiClient.post('/api/sessions', {
        model,
        title,
      });
      const session = response.data;
      return {
        id: session.id,
        title: session.title,
        model: session.model,
        messages: [],
        createdAt: new Date(session.createdAt),
        updatedAt: new Date(session.updatedAt),
      };
    } catch (error) {
      console.error('Error creating session:', error);
      throw error;
    }
  },

  // 删除会话
  deleteSession: async (sessionId: string): Promise<boolean> => {
    try {
      const response = await apiClient.delete(`/api/sessions/${sessionId}`);
      return response.data.success;
    } catch (error) {
      console.error('Error deleting session:', error);
      return false;
    }
  },
};

